<template>
    <div class="department-config">
        <div class="page-header">
            <h2>部门配置</h2>
            <div>
                <el-button type="primary" @click="openAddDialog">添加部门</el-button>
                <el-button class="refreshSuperiorRelation" :icon="Refresh" @click="RefreshDepartments" circle />
            </div>
        </div>

        <!-- 部门列表 -->
        <TreeDepartments ref="treeRef" @edit-department="openEditDialog"></TreeDepartments>

        <!-- 添加/编辑部门弹窗 -->
        <el-dialog v-model="dialogVisible" title="部门配置" width="400px" :before-close="closeDialog">
            <!-- 调整表单的整体样式 -->
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="dialog-form">
                <!-- 部门名称 -->
                <el-form-item label="部门名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入部门名称" />
                </el-form-item>

                <!-- 上级部门关系 -->
                <el-form-item label="上级部门" prop="superiorRelation">
                    <el-cascader v-model="form.superiorRelation" placeholder="请选择上级部门关系" :options="options"
                        :props="{ checkStrictly: true }" @change="handleChange" />
                    <el-button class="refreshSuperiorRelation" :icon="Refresh" @click="refreshOptions" size="small"
                        circle />
                </el-form-item>

                <!-- 部门经理 ID -->
                <el-form-item label="部门经理 ID">
                    <el-input v-model="form.managerId" placeholder="请输入部门经理 ID" />
                </el-form-item>

                <!-- 启用状态 -->
                <el-form-item label="启用状态">
                    <el-switch v-model="form.enable" active-text="启用" inactive-text="禁用" />
                </el-form-item>

            </el-form>

            <!-- 底部按钮区域 -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="closeDialog" size="medium">取消</el-button>
                <el-button type="primary" @click="saveDepartment" size="medium">保存</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { onMounted, inject, ref, reactive } from 'vue';
const axios = inject('$axios'); // 从全局属性注入
import { Refresh } from '@element-plus/icons-vue'

import TreeDepartments from './TreeDepartments.vue';

const treeRef = ref(null)

//上级部门选择内容
const options = ref([])

// 表单相关数据
const dialogVisible = ref(false);
const form = ref({
    id: 0,
    name: '',
    superiorRelation: '',
    managerId: 0,
    enable: true,
    createTime: '',
    updateTime: '',
    createBy: null,
    updateBy: null,
    isDeleted: false,
});

//获取部门关系
let superiorRelation = '';
const handleChange = (value) => {
    const newValue = value.map(item => item.toString().toLowerCase()).join(','); // 将选中的值转为小写字符串
    superiorRelation = newValue
}

// 打开添加部门对话框
const openAddDialog = () => {
    form.value = {
        id: null,
        name: '',
        superiorRelation: '',
        managerId: null,
        enable: true,
        createTime: '',
        updateTime: '',
        createBy: null,
        updateBy: null,
        isDeleted: false,
    };
    dialogVisible.value = true;
};

// 打开编辑部门对话框
const openEditDialog = (row) => {
    if (typeof row.superiorRelation === 'string') {
        // 保存原始字符串
        const originalRelation = row.superiorRelation;
        // 将字符串转换为数组
        row.superiorRelation = originalRelation.split(',');
    } else {
        // 如果不是字符串，则处理数据并回退到原值
        handleChange(row.superiorRelation);
        row.superiorRelation = Array.isArray(row.superiorRelation)
            ? row.superiorRelation
            : []; // 如果不是数组，设置为空数组
    }
    form.value = { ...row };
    dialogVisible.value = true;
};

// 关闭对话框
const closeDialog = () => {
    dialogVisible.value = false;
};

const formRef = ref(null); // 这里声明 formRef

const rules = {
    name: [
        { required: true, message: '部门名称不能为空', trigger: 'blur' }
    ],
    superiorRelation: [
        { required: true, message: '部门关系不能为空', trigger: 'blur' }
    ]
}

// 保存部门
const saveDepartment = async () => {
    //校验
    const valid = await new Promise((resolve, reject) => {
        formRef.value.validate((valid) => {
            if (!valid) {
                ElMessage.error('请完善必填项');
                return (new Error('请完善必填项'));
            } else {
                resolve(valid)
            }
        })
    })


    //传参数据
    var dataParam = {
        'Id': form.value.id ?? 0,
        'Name': form.value.name,
        'SuperiorRelation': superiorRelation,
        'ManagerId': form.value.managerId ?? 0,
        'Enable': form.value.enable,
    }

    if (dataParam.Id > 0) {
        // 编辑部门，执行更新操作
        const result = await axios.post('/Department/EditDepartmentAsync', dataParam);
        if (result.statusCode == 200 && result.success == true) {
            GetDepartmentsByCascaderAsync();
            if (treeRef.value) {
                treeRef.value.ReloadData(); // 调用子组件的刷新方法
            }
            ElMessage.success(result.message);
        } else {
            ElMessage.error(result.message);
        }
    } else {
        // 添加部门，执行添加操作
        const result = await axios.post('/Department/AddDepartmentAsync', dataParam);
        if (result.statusCode == 200 && result.success == true) {
            GetDepartmentsByCascaderAsync();
            if (treeRef.value) {
                treeRef.value.ReloadData(); // 调用子组件的刷新方法
            }
            ElMessage.success(result.message);
        } else {
            ElMessage.error(result.message);
        }
    }
    closeDialog();
};

//获取上层部门层级数据
const GetDepartmentsByCascaderAsync = async () => {
    var result = await axios.get('/Department/QueryDepartmentsByCascaderAsync')
    if (result.statusCode == 200 && result.success == true) {
        options.value = result.response
    }
}

//刷新上层部门层级数据
const refreshOptions = async () => {
    await GetDepartmentsByCascaderAsync();
}

//手动刷新页面数据
const RefreshDepartments = () => {
    treeRef.value.ReloadData(); // 调用子组件的刷新方法
    ElMessage.success('刷新成功');
}

onMounted(async () => {
    await GetDepartmentsByCascaderAsync();
})

</script>


<style scoped>
.page-header {
    display: flex;
    justify-content: space-between; 
}

.refreshSuperiorRelation {
    margin-left: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    /* 使按钮右对齐 */
    padding: 10px 20px;
    /* 增加一些内边距 */
}

.dialog-footer .el-button {
    width: 80px;
    margin-left: 20px;
    /* 按钮之间的间距 */
}

.el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
}

.el-button--primary:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
}
</style>